# app/services/friend_service.py
from app import db
from flask import current_app,request
import os
import shutil
import uuid
from datetime import datetime
from app.models import User, Friend, FriendGroup

def getFriendList(friends):
    friendList = []
    if not friends:
        return friendList
    for friend in friends:
        user = User.query.filter_by(user_id=friend.friend_id).first()
        friendList.append({
            'friendship_id': friend.friendship_id,
            'user_id': friend.user_id,
            'friend_id': friend.friend_id,
            'state': friend.status,
            'group_id': friend.group_id,
            'username': user.username,
            'avatar_url': user.avatar_url,
        })
    return friendList

def getAptFriendList(friends):
    friendList = []
    if not friends:
        return friendList
    for friend in friends:
        user = User.query.filter_by(user_id=friend.user_id).first()
        friendList.append({
            'friendship_id': friend.friendship_id,
            'user_id': friend.user_id,
            'friend_id': friend.friend_id,
            'state': friend.status,
            'group_id': friend.group_id,
            'username': user.username,
            'avatar_url': user.avatar_url,
        })
    return friendList

class FriendService:
    @staticmethod
    def get_friend_group(user_id:str):
        friendGroups = FriendGroup.query.filter_by(user_id=user_id).all()
        applicateFriends = Friend.query.filter_by(friend_id=user_id,status='pending').all()
        friends = Friend.query.filter_by(user_id=user_id,status='accepted').all()
        blacks = Friend.query.filter_by(user_id=user_id,status='blocked').all()
        aptFriendList = getAptFriendList(applicateFriends)
        allFriendList = getFriendList(friends)
        blackList = getFriendList(blacks)
        groupList = []
        for group in friendGroups:
            print(group.group_id,group.group_name)
            gfriends = Friend.query.filter_by(group_id=group.group_id,status='accepted').all()
            friendList = getFriendList(gfriends)
            groupList.append({
                'group_id': group.group_id,
                'user_id': group.user_id,
                'group_name': group.group_name,
                'position': group.position,
                'friendList': friendList
            })

        result = {
            'applicationList': aptFriendList,
            'allFriendList': allFriendList,
            'blackList': blackList,
            'groupList': groupList,
        }

        return result

    @staticmethod
    def add_friend_group(user_id:str,group_name:str):
        group_id = str(uuid.uuid4())

        groupCount = FriendGroup.query.filter_by(user_id=user_id).count()

        group = FriendGroup(
            group_id=group_id,
            user_id=user_id,
            group_name=group_name,
            position=groupCount + 1,
        )

        db.session.add(group)
        db.session.commit()

        return '操作成功'

    @staticmethod
    def add_friend(user_id:str,friend_id:str):
        user = User.query.filter_by(user_id=friend_id).first()
        if not user:
            return '不存在该用户', 403
        friend = Friend.query.filter_by(user_id=user_id,friend_id=friend_id).first()
        friendR = Friend.query.filter_by(user_id=friend_id,friend_id=user_id).first()
        if friend and friendR:
            return '已添加该用户为好友', 403
        elif friend:
            return '已发送邀请，等待对方同意', 401

        friendship_id = str(uuid.uuid4())

        friend = Friend(
            friendship_id=friendship_id,
            user_id=user_id,
            friend_id=friend_id,
            status='pending',
            created_at=datetime.now()
        )

        db.session.add(friend)
        db.session.commit()

        return '已发送好友申请'

    @staticmethod
    def delete_friend(user_id: str, friend_id: str):
        friend = Friend.query.filter_by(user_id=user_id, friend_id=friend_id).first()
        friendR = Friend.query.filter_by(user_id=friend_id, friend_id=user_id).first()

        db.session.delete(friendR)
        db.session.delete(friend)

        db.session.commit()

        return '已删除好友'

    @staticmethod
    def change_friend_status(user_id:str,friend_id:str,status:str):
        friend = Friend.query.filter_by(user_id=friend_id,friend_id=user_id,status='pending').first()
        if not friend:
            return '不存在该申请',404

        if status == 'refused':
            db.session.delete(friend)
            db.session.commit()
            return 'success'

        friend.status = status
        friendship_id = str(uuid.uuid4())
        rfriend = Friend.query.filter_by(user_id=user_id,friend_id=friend_id).first()
        if rfriend:
            rfriend.status='accepted'
            db.session.commit()
            return 'success'
        else:
            rfriend = Friend(
                friendship_id=friendship_id,
                user_id=user_id,
                friend_id=friend_id,
                status='accepted',
                created_at=friend.created_at
            )
            db.session.add(rfriend)
            db.session.commit()

            return 'success'

    @staticmethod
    def movo_to_group(user_id:str,friend_id:str,group_id:str):
        friend = Friend.query.filter_by(user_id=user_id,friend_id=friend_id).first()
        friend.group_id = group_id
        db.session.commit()

        return 'success'

